import { logMgr } from "./LogMgr";

class EventMgr {
    public static instance: EventMgr = null
    public static getInstance() {
        if (!EventMgr.instance) {
            EventMgr.instance = new EventMgr()
        }
        return EventMgr.instance
    }

    private eventTarget: cc.EventTarget = null;
    constructor() {
        this.eventTarget = new cc.EventTarget();
    }

    on(eventName: string, callback: Function, target: any) {
        if (!target || !callback) {
            logMgr.warn(`EventMgr on is null eventName = [${eventName}], target = [${target}], callback [${callback}]`)
            return false
        }
        // @ts-ignore
        if (this.eventTarget.hasEventListener(eventName, callback, target)) {
            logMgr.warn(`EventMgr add exist eventName [${eventName}] in target = `, target)
            return false
        }

        this.eventTarget.on(eventName, callback, target)
        return true
    }

    off(eventName: string, callback: Function, target: any) {
        if (!target) {
            logMgr.warn(`EventMgr removeByName target is null eventName ${eventName}`)
            return false
        }
        this.eventTarget.off(eventName, callback, target)
        return true
    }

    targetOff(target: any) {
        target && this.eventTarget.targetOff(target)
    }

    emit(eventName: string, data?: any) {
        eventName && this.eventTarget.emit(eventName, data)
    }

    clear() {
        this.eventTarget.clear()
    }
}

export let eventMgr = EventMgr.getInstance()
